<?php

class Adept_Db_ActiveRecord_Collection implements ArrayAccess, Countable {

    protected $ids = array(); 
    protected $collection = array();
    protected $collectionClass;
    
    public function __construct() 
    {
    }    
    
    /**
     * @return Adept_Db_IActiveRecord
     */
    protected function createObject()
    {
        $class = $this->collectionClass;
    	return new $class();
    }
    
    protected function resolveObject($id)
    {
    	$record = $this->createObject();
    	$record->loadById($id);
    	
    	$this->collection[$id] = $record;
    	return $record;
    }

    public function getIds() 
    {
        return $this->ids;
    }
    
    public function setIds($ids) 
    {
        $this->ids = $ids;
    }
    
    public function offsetGet($offset) 
    {        
        if (isset($this->collection[$offset])) {
            return $this->collection[$offset];
        }
        if (in_array($offset, $this->ids)) {
            return $this->resolveObject($offset);
        }
        return null;
    }    
    
    public function offsetSet($offset, $value) 
    {
        if (!in_array($offset, $this->ids)) {
            $this->ids[] = $offset;
        }
        $this->collection[$offset] = $value;
        
    }    
    
    public function offsetUnset($offset) 
    {        
    }    
    
    public function offsetExists($offset) 
    {
        return in_array($offset, $this->ids);
    }    
    
    public function count() 
    {
        return count($this->ids);
    }    
    
}
